package com.gitee.wsl.mathematics.function

/**
 * Enum class representing different strategies for calculating Fibonacci numbers.
 */
enum class Fibonacci {
    ITERATIVE {
        override fun invoke(index: Long): Long =
            if (index < 2) {
                index
            } else {
                var previous = 0L
                var current = 1L
                var remainingSteps = index
                do {
                    val sum = previous + current
                    previous = current
                    current = sum
                } while (remainingSteps-- > 1)
                previous
            }
    },
    RECURSIVE {
        override fun invoke(index: Long): Long = if (index < 2) {
            index
        } else {
            this(index - 1) + this(index - 2)
        }
    },
    ;

    /**
     * Calculates the Fibonacci number at the given index using the specified strategy.
     *
     * @param index The index of the Fibonacci number.
     * @return The Fibonacci number at the given index.
     */
    abstract operator fun invoke(index: Long): Long
}

/**
 * Calculates the Fibonacci number at the given index using recursion.
 *
 * @receiver The index of the Fibonacci number.
 * @return The Fibonacci number at the given index.
 */
fun Int.toFibonacciSequence(): Int {
    if (this <= 1) {
        return this
    }
    return (this - 1).toFibonacciSequence() + (this - 2).toFibonacciSequence()
}

/**
 * Calculates the Fibonacci number at the given index using iteration.
 *
 * @param num The index of the Fibonacci number.
 * @return The Fibonacci number at the given index.
 */
fun fibonacciAt(num: Int) =
    run {
        tailrec fun fibonacciAcc(
            count: Int,
            prev: Long,
            curr: Long,
        ): Long = when (count == 0) {
            true -> curr
            false -> fibonacciAcc(count - 1, prev + curr, prev)
        }
        fibonacciAcc(num, 1, 0)
    }
